package com.jy.app.lib.update;

import android.app.DownloadManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.content.FileProvider;

import java.io.File;
import java.io.IOException;
import java.util.List;


public class UpDateAppService extends Service {
	DownloadAppConfig dlaConfig;
	long id = -1;
	private DownloadManager dowanloadmanager = null;
	private String url = "";

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		dowanloadmanager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
		dlaConfig = new DownloadAppConfig(this);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent,Service.START_REDELIVER_INTENT, startId);
	}

	@Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		try{
			id = dlaConfig.getDownLoadId();
			if (intent != null) {
				url = intent.getStringExtra("url");
			}
			if (id != -1) {
				downloadStatus();
			} else {
//			if (UpdateManager.context != null&&new Date().getTime() >= dlaConfig.getNetUpDateTime()) {
				AppUpdateManager.checkUpdate(UpdateManager.context,url);
//			} else {
//				UpdateManager.context  = null;
//				stopSelf();
//			}

			}
		}catch (Exception e){

		}

	}

	@Override
	public void onDestroy() {
		if(UpdateManager.mHander!=null){
			UpdateManager.mHander.sendEmptyMessage(UpdateManager.CHECK_UPDATE_IS_CLICK);
		}
		super.onDestroy();
	}

	private void downloadStatus() {
		DownloadManager.Query query = new DownloadManager.Query();
		query.setFilterById(id);
		Cursor c = dowanloadmanager.query(query);
		if (c != null && c.moveToFirst()) {
			int status = c.getInt(c
					.getColumnIndex(DownloadManager.COLUMN_STATUS));
			switch (status) {
				case DownloadManager.STATUS_SUCCESSFUL:
					File file = new File(dlaConfig.getDownLoadPathName());
					installApk(file,this);
					stopSelf();
					dlaConfig.setDownLoadId(-1);
					break;
				default:
					dowanloadmanager.remove(id);
					if (UpdateManager.context != null) {
						AppUpdateManager.checkUpdate(UpdateManager.context,url);
					} else {
						stopSelf();
					}
					break;
			}
		}else{
			dowanloadmanager.remove(id);
			if (UpdateManager.context != null) {
				AppUpdateManager.checkUpdate(UpdateManager.context,url);
			} else {
				stopSelf();
			}
		}
	}

	public static void installApk(File updateFile, Context context) {
		try {
			String[] command = {"chmod", "777", updateFile.getPath() };
			ProcessBuilder builder = new ProcessBuilder(command);
			builder.start();
		} catch (IOException e) {
		}
		try{
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			Uri apkUri;
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                apkUri = FileProvider.getUriForFile(context, context.getPackageName()+".provider", updateFile);
                context.grantUriPermission(context.getPackageName(),apkUri,Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			} else {
				apkUri = Uri.fromFile(updateFile);
			}
			intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
			// 查询所有符合 intent 跳转目标应用类型的应用，注意此方法必须放置在 setDataAndType 方法之后
			List<ResolveInfo> resolveLists = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
			// 然后全部授权
			for (ResolveInfo resolveInfo : resolveLists){
				String packageName = resolveInfo.activityInfo.packageName;
				context.grantUriPermission(packageName, apkUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
			}
			context.startActivity(intent);
		}catch (Exception e){
			e.printStackTrace();
		}
		if(UpdateManager.mHander!=null){
			UpdateManager.mHander.sendEmptyMessage(UpdateManager.CHECK_UPDATE_IS_CLICK);
		}
	}
}
